#include <iostream>
#include <string>
#include <cassert>
using namespace std;



class Any{
private:
    class holder{
    public:
        virtual ~holder(){}
        virtual const std::type_info& type()=0;
        virtual holder* clone()=0;

    };

    template<class T>
    class placehoder :public holder{
    public:
        placehoder(const T&val):_val(val){}
        virtual ~placehoder(){}
        //获取子类对象保存的数据类型
        virtual const std::type_info& type(){return typeid(T);}
        //针对当前的对象自身，克隆出一个新的子类对象
        virtual holder* clone(){return new placehoder(_val);}
        T _val;
    };
    holder* _content;

    
public:
    Any():_content(nullptr) {}
    template<class T>
    Any(const T&val):_content(new placehoder<T>(val)){}
    Any(const Any &other):_content(other._content?_content->clone():nullptr){}
    ~Any(){delete _content;}

    Any& Swap(Any& other){
        std::swap(_content,other._content);
        return *this;
    }
    
    template<class T>
    T* get(){//返回子类保存的数据指针
        assert(typeid(T)==_content->type());
        return &(((placehoder<T>*)_content)->_val);
    }
    template<class T>
    Any& operator=( T &val){//赋值运算符重载函数
        Any tmp(val);
        Swap(tmp);
        return *this;
    }
    Any& operator=( Any other){
        Swap(other);
        return *this;
    }
};


int main()
{
    Any a;
    a=10;
    int* pa=a.get<int>();
    cout<<pa<<endl;
    cout<<*pa<<endl;
    a=string("abc");
    string* ps=a.get<string>();
    cout<<*ps<<endl;
    return 0;
}